<template>
  <div class="phone-container">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="手机名称">
          <el-input v-model="searchForm.name" placeholder="请输入手机名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机型号">
          <el-input v-model="searchForm.model" placeholder="请输入手机型号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleReset">重置</el-button>
          <el-button type="info" @click="loadData">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading" element-loading-text="加载中...">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="手机图片" width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.image || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'"
            fit="contain"
            :preview-src-list="scope.row.image ? [scope.row.image] : []">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="手机名称"></el-table-column>
      <el-table-column prop="model" label="手机型号"></el-table-column>
      <el-table-column prop="firmwareCount" label="固件数量" width="100"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="success" size="small" @click="handleVersion(scope.row)">固件管理</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px">
      <el-form :model="form" :rules="rules" ref="phoneForm" label-width="100px">
        <el-form-item label="手机名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入手机名称"></el-input>
        </el-form-item>
        <el-form-item label="手机型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入手机型号"></el-input>
        </el-form-item>
        <el-form-item label="手机图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/files/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { phoneApi } from '@/utils/api'

export default {
  name: 'Phone',
  data() {
    return {
      searchForm: {
        name: '',
        model: ''
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      dialog: {
        title: '',
        visible: false,
        type: 'add' // add 或 edit
      },
      form: {
        id: null,
        name: '',
        model: '',
        image: ''
      },
      rules: {
        name: [{ required: true, message: '请输入手机名称', trigger: 'blur' }],
        model: [{ required: true, message: '请输入手机型号', trigger: 'blur' }],
        image: [{ required: false, message: '请上传手机图片', trigger: 'change' }]
      },
      loading: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 加载列表数据
    loadData() {
      // 显示加载状态
      this.loading = true;
      this.tableData = [];
      
      // 准备查询参数 - 确保传递的name和model在有值时才不为null
      const params = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        name: this.searchForm.name ? this.searchForm.name.trim() : null,
        model: this.searchForm.model ? this.searchForm.model.trim() : null
      }
      
      console.log('发起查询请求，参数:', JSON.stringify(params));
      
      // 加载数据
      phoneApi.getPhonePage(params)
        .then(res => {
          this.loading = false;
          console.log('接口返回数据:', JSON.stringify(res));
          
          if (res.code === 200 || res.code === "200") {
            if (res.data && res.data.list) {
              this.tableData = res.data.list;
              this.page.total = res.data.total || 0;
              
              if (this.tableData.length === 0) {
                this.$message.info('没有找到符合条件的数据');
              }
            } else {
              this.tableData = [];
              this.page.total = 0;
              this.$message.warning('返回数据格式不正确');
            }
          } else {
            this.tableData = [];
            this.page.total = 0;
            this.$message.error('获取数据失败：' + res.msg);
          }
        })
        .catch(err => {
          this.loading = false;
          console.error('获取手机设备列表错误:', err);
          this.tableData = [];
          this.page.total = 0;
          this.$message.error('获取数据失败：' + (err.message || '未知错误'));
        });
    },
    
    // 查询按钮
    handleSearch() {
      console.log('点击查询按钮，搜索条件:', JSON.stringify(this.searchForm));
      // 重置到第一页并立即查询
      this.page.pageNum = 1;
      this.$nextTick(() => {
        this.loadData();
      });
    },
    // 新增按钮
    handleAdd() {
      this.dialog.title = '新增手机设备'
      this.dialog.type = 'add'
      this.dialog.visible = true
      this.form = {
        id: null,
        name: '',
        model: '',
        image: ''
      }
    },
    // 编辑按钮
    handleEdit(row) {
      this.dialog.title = '编辑手机设备'
      this.dialog.type = 'edit'
      this.dialog.visible = true
      this.form = JSON.parse(JSON.stringify(row))
    },
    // 固件管理按钮
    handleVersion(row) {
      this.$router.push({ name: 'Version', query: { phoneId: row.id } })
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除该手机设备及关联的固件版本信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        phoneApi.deletePhone(row.id).then((res) => {
          if (res.code === 200 || res.code === "200") {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error('删除失败：' + res.msg)
          }
        }).catch(err => {
          console.error('删除手机设备错误:', err)
          this.$message.error('删除失败：' + (err.message || '未知错误'))
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.phoneForm.validate((valid) => {
        if (valid) {
          // 确保提交数据格式正确
          const submitData = { ...this.form }
          
          if (this.dialog.type === 'add') {
            phoneApi.addPhone(submitData)
              .then((res) => {
                if (res.code === 200 || res.code === "200") {
                  this.$message.success('新增成功')
                  this.dialog.visible = false
                  this.loadData()
                } else {
                  this.$message.error('新增失败：' + res.msg)
                }
              })
              .catch(err => {
                console.error('新增手机设备错误:', err)
                this.$message.error('新增失败：' + (err.message || '未知错误'))
              })
          } else {
            phoneApi.updatePhone(submitData)
              .then((res) => {
                if (res.code === 200 || res.code === "200") {
                  this.$message.success('更新成功')
                  this.dialog.visible = false
                  this.loadData()
                } else {
                  this.$message.error('更新失败：' + res.msg)
                }
              })
              .catch(err => {
                console.error('更新手机设备错误:', err)
                this.$message.error('更新失败：' + (err.message || '未知错误'))
              })
          }
        } else {
          return false
        }
      })
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.page.pageSize = val
      this.loadData()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.loadData()
    },
    // 图片上传成功
    handleAvatarSuccess(res) {
      if (res.code === '200' || res.code === 200) {
        this.form.image = res.data
        this.$message.success('图片上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 重置按钮
    handleReset() {
      this.searchForm = {
        name: '',
        model: ''
      }
      this.loadData()
    }
  }
}
</script>

<style scoped>
.phone-container {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 图片上传样式 */
.avatar-uploader {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style> 